package com.hang.ad.index;

import com.alibaba.fastjson.JSON;
import com.hang.ad.dump.DataConstant;
import com.hang.ad.dump.table.*;
import com.hang.ad.handler.AdLevelDataHandler;
import com.hang.ad.mysql.constant.OpType;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Component
@DependsOn("dataTable")
public class IndexFileLoader {
    @PostConstruct
    public void init(){
        List<String> plan = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_PLAN));
        plan.forEach(d -> AdLevelDataHandler.handleLevel2(JSON.parseObject(d, AdPlanTable.class), OpType.ADD));

        List<String> creative = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_CREATIVE));
        creative.forEach(d -> AdLevelDataHandler.handleLevel2(JSON.parseObject(d, AdCreativeTable.class), OpType.ADD));

        List<String> unit = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT));
        unit.forEach(d-> AdLevelDataHandler.handleLevel3(JSON.parseObject(d, AdUnitTable.class), OpType.ADD));

        List<String> creativeUnit = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_CREATIVE_UNIT));
        creativeUnit.forEach(d -> AdLevelDataHandler.handleLevel3(JSON.parseObject(d, AdCreativeUnitTable.class), OpType.ADD));

        List<String> district = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_DISTRICT));
        district.forEach(d-> AdLevelDataHandler.handleLevel4(JSON.parseObject(d, AdUnitDistrictTable.class), OpType.ADD));


        List<String> it = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_IT));
        it.forEach(d -> AdLevelDataHandler.handleLevel4(JSON.parseObject(d, AdUnitItTable.class), OpType.ADD));

        List<String> keyword = loadFile(String.format("%s%s", DataConstant.DATA_ROOT_DIR, DataConstant.AD_UNIT_KEYWORD));
        keyword.forEach(d -> AdLevelDataHandler.handleLevel4(JSON.parseObject(d, AdUnitKeywordTable.class), OpType.ADD));



    }

    private List<String> loadFile (String fileName){
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))){
            return reader.lines().collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
